package cn.zijian.wechat.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import cn.zijian.models.Message;
import cn.zijian.wechat.R;

/**
 * Created by Administrator on 2017/12/13.
 */

public class MessageAdapter extends ArrayAdapter<Message>
{

    //存放布局文件的资源ID
    private int resourceID;

    public MessageAdapter(@NonNull Context context, int resource, @NonNull List<Message> objects)
    {
        super(context, resource, objects);
        resourceID = resource;
    }

    /**
     * TODO 对该类进行二次封装 以便其它Fragment复用
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
    {
        Message message = (Message) getItem(position);
        View view = null;
        ViewHolder viewHolder;
        if(convertView == null)
        {
            view = LayoutInflater.from(getContext()).inflate(resourceID, parent, false);
            viewHolder = new ViewHolder();
            //头像
            viewHolder.imageAvatarUrl = (ImageView) view.findViewById(R.id.imageAvatarUrl);


            //消息内容
            viewHolder.txtMessageBody = view.findViewById(R.id.txtMessageBody);

            //时间
            viewHolder.txtReceiveTime = view.findViewById(R.id.txtReceiveTime);

            //昵称
            viewHolder.txtNickName = (TextView) view.findViewById(R.id.txtNickName);
            view.setTag(viewHolder);
        }
        else
        {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        viewHolder.imageAvatarUrl.setImageResource(message.getAvatarUrl());
        viewHolder.txtMessageBody.setText(message.getMessageBody());
        viewHolder.txtReceiveTime.setText(message.getReceiveTime());
        viewHolder.txtNickName.setText(message.getNickName());

        return view;
    }

    class ViewHolder
    {
        ImageView imageAvatarUrl;
        TextView txtMessageBody;
        TextView txtReceiveTime;
        TextView txtNickName;
    }
}
